package com.emapp.lccode.fragment

import android.os.Bundle
import androidx.lifecycle.Observer
import com.emapp.lccode.R
import com.emapp.lccode.activity.OrderPaiInforKtActivity
import com.emapp.lccode.activity.ReportInforKtActivity
import com.emapp.lccode.adapter.MyOrderKtAdapter
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.BaseFragment1
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusConfig.REFRESH_ADDRESS
import com.emapp.lccode.base.EventBusConfig.SET_END_DATE
import com.emapp.lccode.base.EventBusConfig.SET_START_DATE
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.OrderKt
import com.emapp.lccode.databinding.FragmentListBinding
import com.emapp.lccode.mode.OrderKtViewModel
import com.emapp.lccode.utils.toStartActivity
import com.emapp.lccode.utils.vertical
import com.hjq.toast.Toaster
import com.kingja.loadsir.core.LoadService
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.ActivityMessenger.finish
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class OrderKTFragment : BaseFragment1<OrderKtViewModel, FragmentListBinding>() {

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>
    var datas: ArrayList<OrderKt> = arrayListOf()
    var start_time = ""
    var end_time = ""
    var status = "0"
    var page = 1
    private val orderKtAdapter: MyOrderKtAdapter by lazy { MyOrderKtAdapter() }

    companion object {
        fun newInstance(status: String): OrderKTFragment {
            val args = Bundle()
            args.putString("status", status)
            val fragment = OrderKTFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        status = arguments?.getString("status").toString()
        mViewBind.rvList.run {
            vertical()
            adapter = orderKtAdapter
        }
        orderKtAdapter.run {
            setOnItemClickListener { adapter, _, position ->
                val item = adapter.items[position]
                var bundle = Bundle()
                bundle.putString("id", item.id)
                bundle.putString("approve_type", item.approve_type)
                bundle.putSerializable("order",item)
//                val check_ids = item.check_admin_ids.split(",").map { it.toInt() }.toTypedArray()
              //  log_e("adminid=" + BaseApplication.instance.adminId) 5
                if (item.check_status == 0) {//未审核
                    if (item.checkIds?.contains(BaseApplication.instance.adminId.toInt())==true) {//我是管理员，去审核
                        toStartActivity(OrderPaiInforKtActivity::class.java, bundle)
                    } else {
                        toStartActivity(ReportInforKtActivity::class.java, bundle)
                    }
                } else if (item.check_status == 1) {//1审核中(管理员已经派单了)
                    if (item.checkIds?.contains(BaseApplication.instance.adminId.toInt()) == true) {//我是接受者，去执行回复和报物料
                        toStartActivity(ReportInforKtActivity::class.java, bundle)
                    } else {
                        toStartActivity(ReportInforKtActivity::class.java, bundle)
                    }

                } else if (item.check_status == 2) {//已经回复了
                    toStartActivity(ReportInforKtActivity::class.java, bundle)

                } else if (item.check_status == 3) {//3审核不通过,4撤销审核
                    toStartActivity(ReportInforKtActivity::class.java, bundle)

                } else if (item.check_status == 4) {//4撤销审核
                    toStartActivity(ReportInforKtActivity::class.java, bundle)

                }
            }
            isEmptyViewEnable = true
            emptyView = layoutInflater.inflate(R.layout.listitem_empty, mViewBind.rvList, false)
        }
        mViewBind.refreshLayout.run {
            setRefreshHeader(ClassicsHeader(activity))
            setRefreshFooter(ClassicsFooter(activity))
            setOnRefreshListener {
                page = 1
                getList()
            }
            setOnLoadMoreListener {
                page++
                getList()
            }
        }
    }

    /**
     * 懒加载
     */
    override fun lazyLoadData() {
        showLoading()
        getList()
    }
private fun getList(){
    mViewModel.getOrderList(start_time, end_time, status, page);
}
    override fun createObserver() {
        mViewModel.run {
            orders.observe(viewLifecycleOwner, Observer { resultState ->
                parseState(resultState, {
                    if (page == 1) {
                        datas.clear()
                        if (it?.data != null) {
                            datas.addAll(it.data)
                            if (it.data.size < BaseConfig.page_count) {
                                mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                            } else {
                                mViewBind.refreshLayout.finishRefresh()
                            }
                        } else {
                            mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                        }
                    } else {
                        if (it?.data != null) {
                            datas.addAll(it.data)
                            if (it.data.size < BaseConfig.page_count) {
                                mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                            } else {
                                mViewBind.refreshLayout.finishLoadMore()
                            }
                        } else {
                            mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                        }
                    }
                    orderKtAdapter.submitList(datas)
                    orderKtAdapter.notifyDataSetChanged()
                }, {
                    Toaster.show(it.errorMsg)
                    mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                })
            })
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            SET_START_DATE -> {
                start_time=event.content
                getList()
            }
            SET_END_DATE -> {
                end_time=event.content
                getList()
            }
            EventBusConfig.REFRESH_ORDER -> {
                getList()
            }
            else -> {}
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBindViewClick() {
//        setOnclickNoRepeat( mViewBind.tvDai) {
//            when (it.id) {
//                R.id.tv_gongdan -> {
//                    toStartActivity(MyOrderActivity::class.java)
//                }
//
//                R.id.tv_dai -> {
//
//                }
//            }
//        }
    }
}